<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>合同编辑|新增</title>
 <%@ include file="/WEB-INF/component/commonCSS.jsp" %> 
  
</head>
<body class="skin-blue sidebar-mini fixed skin-blue-light-frame">
    <section class="content-header">
        <h1>合同<%= "0".equals(request.getParameter("opType"))? "新增" : "编辑" %></h1>
        <ol class="breadcrumb">
            <li><a href="${ctx}/home.jsp"><i class="fa fa-home"></i>首页</a></li>
            <li class="active"><a href="#">合同管理</a></li>
            <li class="active"><a href="#">合同查看</a></li>
        </ol>
    </section>
    <section class="content">
        	<div class=" box box-success">
	    			<form id="submitForm" role="form" class="form-horizontal" action="${ctx}/contract/saveOrUpdateContract.html">
	    		      <div class="box-body">
	    		      	<div id="contractPartyAndDrug" style="float:left;width:44%"> 
	    		      		<div class="form-group form-group-xs" id="partyA">
		                        <input id="partyAName" name="partyAName" class="form-control" readonly="readonly" placeholder="合同甲方" disabled="disabled"  type="text" value="${defaultPartyA}" style="float:left;width:200px;margin-left:63px"/>
	                            <input id="partyAId" name="partyAId" type="hidden" value="${defaultPartyAId }"/>
	                            <a id="partyChoose" href="javascript:void(0)" onclick="selectParty(this.id);" class="btn btn-default btn-sm" style="margin-left:10px">选择</a>
		                    </div>
		                    <div class="form-group form-group-xs">
		                    	<ol style="list-style-type:none" id="partys">
			                    	<li id="party1">
				                    	<i class="fa fa-plus" id="partyPlus1" style="color: blue;margin-right: 15px; float:left" onclick="addDiv(this.id)"></i>
	                            		<input id="party1Name" class="form-control" readonly="readonly" placeholder="合同乙方" disabled="disabled"  type="text" style="float:left;width:200px">
	                            		<input id="party1Id" type="hidden" value=""/>
	                            		<a id="partyChoose1" href="javascript:void(0)" onclick="selectParty(this.id);" class="btn btn-default btn-sm" style="margin-left:10px">选择</a>
	                            		<ol style="list-style-type:none" id="party1drugs">
	                            			<li id="party1drugs1">
	                            				<i class="fa fa-plus" id="party1drugs1plus" style="color: blue;margin-right: 15px; float:left" onclick="addDrug(this.id)"></i>
	                            				<input id="party1drugs1Name" class="form-control" readonly="readonly" placeholder="药品" disabled="disabled"  type="text" style="float:left;width:160px">
	                            				<input id="party1drugs1Id" type="hidden" value=""/>
	                            				<a id="party1drugs1select" href="javascript:void(0)" onclick="selectDrug(this.id);" class="btn btn-default btn-sm" style="margin-left:10px">选择</a>
	                            			</li>
	                            		</ol>
			                    	</li>
		                    	</ol>
		                    </div>
		                    <input type="hidden" value="${optType}" id="optType" name="optType">
		                    <input type="hidden" value="" id="txtContent" name="txtContent">
		                    <input type="hidden" value="" id="partyAndDrugData" name="partyAndDrugData">
	                	</div>
	    		      	<div id="contractModel" style="float:right;width:56%">
		                 	<div class="form-group form-group-xs">
		                        <label>合同名称：</label>
		                        <input class="form-control" name="contractTitle" 
		                        style="width: 300px;" id="contractTitle" placeholder="合同名称" type="text" maxlength="200">
		                    </div>
				            <div class="form-group form-group-xs">
								<label>所属项目：</label> 
								<select class='form-control' id="projId" name="projId"
									style="width: 300px;">
									<option value="">请选择</option>
									<c:forEach items="${projectList}" var="project">
										<option value="${project.projId }">${project.name}</option>
									</c:forEach>
								</select>
							</div>
		                    <div class="form-group form-group-xs">
		                        <div class="col-sm-9 text-left">
		                            <div id="editor" style="height:400px;width:600px" name="content">
		                            </div>
		                        </div>
		                    </div>
		                    <input type="hidden" value="${optType}" id="optType" name="optType">
		                    <input type="hidden" value="" id="txtContent" name="txtContent">
		                    <!-- 保存合同模板id -->
		                    <input type="hidden" value="${contractModel.contractModelId}" id="contractModelId" name="contractModelId">
	                	</div>
	                </div>
	                <div class="box-footer text-center">
	                    <a onclick ="save()" class="btn btn-success btn-sm">保 &nbsp;存</a>
	                    <a onclick ="back()" class="btn btn-danger btn-sm">返&nbsp;回</a>
	                </div>
	               </form>
	              </div>
    </section>
     <%@ include file="/WEB-INF/component/commonJS.jsp" %>  
     <script src="${ctx}/lib/plugins/ueditor/lang/zh-cn/zh-cn.js"></script>
    <script type="text/javascript">
        var partyArray = new Array();
        $("#partys").data("partyNum", 1);//将数据存储在元素中
        $("#party1drugs").data("drugsNum", 1);
        function addDiv(id){
        	var partyFatherId = $("#"+id).parent().parent().attr("id");//爷爷元素id
        	var partyBnum = $("#partys").data("partyNum");
        	$("#partyPlus"+partyBnum).attr({ "class": "fa fa-times", "onclick": "removeDiv(this.id)" });
        	partyBnum = partyBnum + 1;
        	var htmlText = "<li id='party"+partyBnum+"'>"
        	+ "<i class='fa fa-plus' id='partyPlus"+partyBnum+"' style='color: blue;margin-right: 15px; float:left' onclick='addDiv(this.id)'></i>"
    		+ "<input id='party"+partyBnum+"Name' class='form-control' readonly='readonly' placeholder='合同乙方' disabled='disabled'  type='text' style='float:left;width:200px'>"
    		+ "<input id='party"+partyBnum+"Id' type='hidden' value=''/>"
    		+ "<a id='partyChoose"+partyBnum+"' href='javascript:void(0)' onclick='selectParty(this.id);' class='btn btn-default btn-sm' style='margin-left:10px'>选择</a>"
    		+ "<ol style='list-style-type:none' id='party"+partyBnum+"drugs'>"
    		+ "<li id='party"+partyBnum+"drugs1'>"
    		+ "<i class='fa fa-plus' id='party"+partyBnum+"drugs1plus' style='color: blue;margin-right: 15px; float:left' onclick='addDrug(this.id)'></i>"
    		+ "		<input id='party"+partyBnum+"drugs1Name' class='form-control' readonly='readonly' placeholder='药品' disabled='disabled'  type='text' style='float:left;width:160px'>"
    		+ "     <input id='party"+partyBnum+"drug1Id' type='hidden' value=''/>"
    		+ "		<a id='party"+partyBnum+"drugs1select' href='javascript:void(0)' onclick='selectDrug(this.id);' class='btn btn-default btn-sm' style='margin-left:10px'>选择</a>"
    		+ "	</li></ol></li>"
        	$("#partys").append(htmlText);
    		$("#party"+partyBnum+"drugs").data("drugsNum",1);
    		$("#partys").data("partyNum",partyBnum);
        }
        
        function addDrug(drugId){
        	var parentId = $("#"+drugId).parent().parent().attr('id');
        	var drugNum = $("#"+parentId).data("drugsNum");
        	$("#"+parentId+""+drugNum+"plus").attr({ "class": "fa fa-times", "onclick": "removeDrug(this.id)" });
        	drugNum = drugNum + 1;
        	var drugHtml = "<li id='"+parentId+""+drugNum+"'>"
    		+  "<i class='fa fa-plus' id='"+parentId+""+drugNum+"plus' style='color: blue;margin-right: 15px; float:left' onclick='addDrug(this.id)'></i>"
    		+  "		<input id='"+parentId+""+drugNum+"Name' class='form-control' readonly='readonly' placeholder='药品' disabled='disabled'  type='text' style='float:left;width:160px'>"
    		+  "	    <input id='"+parentId+""+drugNum+"Id' type='hidden' value=''/>"
    		+  "		<a id='"+parentId+""+drugNum+"select' href='javascript:void(0)' onclick='selectDrug(this.id);' class='btn btn-default btn-sm' style='margin-left:10px'>选择</a>"
    		+  "	</li>";
        	$("#"+parentId).append(drugHtml);
        	$("#"+parentId).data("drugsNum",drugNum);
        }
        
        function removeDrug(id){
        	$("#"+id).parent().remove();
        }
        
        function removeDiv(id){
        	$("#"+id).parent().remove();
        }
        
        function getPartyAndDrugData(){
        	var children = $("#partys").children("li");
        	var jsonString = "[";
        	for(var i = 0; i< children.length;i++){
        		jsonString+= "{party:'"+children.eq(i).children("input[type='hidden']").val()+"'";
        	    var partyLiId = children.eq(i).attr("id");
        		var drugChilds = $("#"+partyLiId).children("ol").children("li");
        		var drugIdString = "";
        		for(var j = 0; j< drugChilds.length; j++){
        			var drug = drugChilds.eq(j);
        			var drugId = drug.children("input[type='hidden']").val();
        			drugIdString = drugIdString+","+drugId;
        		}
        		//drugIdString = drugIdString.slice(1, jsonString.length);
        		jsonString+= ", drugs:'"+drugIdString +"'},";
        	}
        	jsonString = jsonString.slice(0,jsonString.length-1);
        	jsonString = jsonString+"]"
            $("#partyAndDrugData").val(jsonString);
        	return jsonString;
        }     
        function selectParty(strPartyId){
        	var strPartyId = $("#"+strPartyId).parent().attr('id');
        	if(strPartyId!="" && null!=strPartyId){
        	   $.HN.dialog.opendialog(1,"生产企业列表","${ctx}/contractSC/toSelectContractPartySC.html?strPartyId="+strPartyId,"800px","400px",operCompResult);
        	}else{
        	   $.HN.dialog.opendialog(1,"生产企业列表","${ctx}/contractSC/toSelectContractPartySC.html","800px","400px",operCompResult);
        	}
        }
        function selectDrug(strDrugId){
        	var strDrugId = $("#"+strDrugId).parent().attr("id");
           if(strDrugId != "" && null != strDrugId){
      		   $.HN.dialog.opendialog(1,"药品列表","${ctx}/contractSC/toSelectContractDrugSC.html?strDrugId="+strDrugId,"800px","400px",operDrugResult);
      	   }else{
      		   $.HN.dialog.opendialog(1,"药品列表","${ctx}/contractSC/toSelectContractDrugSC.html","800px","400px",operDrugResult);
      	   }
        }
        function operCompResult(val){
            var str = val.split("|$");
            var partyName = str[1];
            var partyId = str[0];
            var partyHtmlId = str[2];
            $("#"+partyHtmlId).children("input[type='hidden']").val(partyId);
            $("#"+partyHtmlId).children("input[type='text']").val(partyName);
            
        }
        function operDrugResult(val){
        	 var str = val.split("|$");
             var drugId = str[0];
             var drugName = str[1];
             var drugHtmlId = str[2];
             $("#"+drugHtmlId).children("input[type='hidden']").val(drugId);
             $("#"+drugHtmlId).children("input[type='text']").val(drugName);
       }
        
        var ue;
        function save(){
        	var jsonDate = getPartyAndDrugData();
        	if(!validate(jsonDate)){
        		return;
        	}
    		$.HN.message.confirm('确定要保存吗？', '', '').on(function (e) {
                   if (e) {
                var ue = UE.getEditor('editor');
                var txtContent = ue.getContent();
                $("#txtContent").val(txtContent)
    			$("#submitForm").ajaxSubmit({
    				 type: 'post',
    				dataType : "json",
    				timeout: 10000,
    				success : function(result) {
    					if (result.success) {
    						$.HN.message.alert("保存成功！", "消息", "success", function() {
    							window.location.href="${ctx}/contractSC/toBidContractListSC.html";
    						});
    					} else {
    						$.HN.message.alert(result.msg || "", "消息", "error");
    					}
    				}
    			});
             }
           });
        }
        function validate(jsonDate){
        	var contractTitle = $.trim($("#contractTitle").val());
        	var projId = $.trim($("#projId").val());
        	var partyAId = $.trim($("#partyAId").val());
        	var partyAName = $.trim($("#partyAName").val());
        	 var ue = UE.getEditor('editor');
             var txtContent = ue.getContent();
            
        	var obj = eval(jsonDate);
			for(var i=0; i < obj.length; i++){
				var partyB = obj[i].party;//获取合同乙方
				var drugs = obj[i].drugs;
				drugs = drugs.substring(1, drugs.length);
				var drugsArray = drugs.split(",");
				if(partyB == null || partyB == ""){
					$.HN.message.alert("存在未填写的合同乙方！", "消息", "info");
					return false;
				}	
				for(var j = 0; j < drugsArray.length;j++){
					var drug = drugsArray[j];
					if(drug == null || drug == ""){
						$.HN.message.alert("存在未填写的药品！", "消息", "info");
						return false;
					}
				}	
			}
    		if (contractTitle == null || contractTitle == "") {
    			$.HN.message.alert("合同名称不能为空！", "消息", "info");
    			return false;
    		} 
    		if (projId == null || projId == "") {
    			$.HN.message.alert("所属项目不能为空！", "消息", "info");
    			return false;
    		} 
    		if ((partyAId == null || partyAId == "")&&(partyAName==null||partyAName=="")) {
    			$.HN.message.alert("合同甲方不能为空！", "消息", "info");
    			return false;
    		}
    		if (txtContent == null || txtContent == "") {
    			$.HN.message.alert("合同内容不能为空！", "消息", "info");
    			return false;
    		} 
    		

    		return true;
        }
        
        function back(){
        	window.location.href="toBidContractListSC.html"
        }
		$(function() {
		    ue = UE.getEditor('editor');
		    var optType = "${optType}";
			ue.ready(function() {
		        	ue.setContent("${contractModel.content}");
			});
		});
    </script>
</body>
</html>
